<template>
  <!-- 线索查询 -->
  <div>
    <TopFilter :list="topFilterList" :cols="3" labelWidth="100" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChangeHandle"
      columnsRef="potenCus_customer_cluesQuery_index_01"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" @click="addHandle">新增</el-button>
        <el-button size="small" type="primary" @click="importHandle">导入</el-button>
        <el-button size="small" type="primary" :loading="exportLoading" @click="exportHandle">导出</el-button>
        <el-button size="small" type="primary" @click="downHandle">模板下载</el-button>
      </template>
    </FilterTable>
    <Drawer :visible.sync="visible" :title="dialogTitle" width="80%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <queryModel :type="handleType" :rowData="formData" @close="closeHandler" />
    </Drawer>
    <BaseDialog :visible.sync="UploadFileIsShow" title="导入" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <importFile title="导入" :actionUrl="actionUrl" @close="successHandler" />
    </BaseDialog>
  </div>
</template>

<script>
import { queryClueSearchList, importClues, exportClues, downloadExcel, exporturl } from '@/api/potenCus/customer/cluesQuery';
import { getUserInfo } from '@/api/potenCus/customer/exhibition';
import { getAllColorByAppIdAndType } from '@/api/potenCus/customer/potenCusManage';
import { getAllModal, queryClueSourceList, getConsultantName, getAllHeatUp } from '@/api/potenCus/customer/potenCusManage';
import { vehicleConfigurationNew } from '@/api/retail/salesmanage/confirmcar'; //获取五级六单
import queryModel from '../cluesQuery/queryModel';
import { region } from '@/api/cms-common/region'; //行政区域
import { dictionary } from '@/utils/dictMixin';
import { getAppId } from '@/assets/js/auth';
import { authority } from '@/utils/authMixin';
import { exportExcelFile } from '@/utils/index';
import { formatDates, forDates } from '@/utils/validate';
import { getDataType, getUser } from '@/assets/js/auth';
import { getLoginUser } from '@/api/cms-api/projectOperating/program/departmentInquire'; //获取登录信息
export default {
  name: 'FailModel',
  mixins: [dictionary, region, authority],
  components: {
    queryModel
  },
  data() {
    return {
      dataType: getDataType('dataType'),
      topFilterList: this.createTopFilters(),
      fetchParams: {},
      dialogTitle: '',
      fetchApi: queryClueSearchList,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      visible: false,
      selectedRows: [], //选中列表中的行
      UploadFileIsShow: false, // 导入弹框
      conf: { add: '新增', show: '信息' },
      form: {
        fileList: []
      },
      actionUrl: '/api/cyxdms.clue/clue/clueRecodeExcelDataImport',
      userId: '',
      exportLoading: false
    };
  },
  created() {
    this.init();
    this.getClueTree();
    this.getAllHeatUp();
  },
  methods: {

    async showHandle(row) {

      debugger
      // TODO:
      const res = await getPotenCusById(row.customerBusinessId, row.clueType);
      this.handleType = 'show';
      this.formDataDetail = res.data;
      let newRow;
      newRow = {
        ...res.data,
        potentialCustomerName: row.customerName,
        potentialCustomerPhone: row.mobilePhone,
        mobile: row.mobilePhone,
        employeeName: row.currentConsultantName,
        customerNo: res.data.customerBusinessId,
        // potentialCustomersId: res.data.customerBusinessId,
        potentialCustomerNo: row.potentialCustomerNo,
        consultant: res.consultant,
        consultantName: res.consultantName,
        // actionId: res.data.clueRecordId,
        driverCard: res.data.certificateNo,
        planActionDate: res.data.planActionDate,
        vehicleUse: res.data['buyCarUse'],
        clueStatus: res.data.clueStatus,
        driveType: 20261002, //默认试驾
        clueType: 70241002 // 后台确定写死
      };
      this.formData = newRow;
      console.log(this.formData, '跳转携带formData');
      this.showHandlerDetail();
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      console.log(pl, '12342354234');
      this.topFilterList.find(item => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find(item => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
      //清除区县
      let district = this.topFilterList.find(item => item.fieldName === 'districtId');
      district.itemList = [];
      district.initialValue = '';
    },
    //初始化所在县市数据
    async initTown(cityId) {
      if (!cityId || cityId == null || typeof cityId == 'undefined') {
        return;
      }
      let td = this.cityData[cityId].children;
      let tl = this.createSubRegionList(td);
      //初始化区县，清除原值
      let district = this.topFilterList.find(item => item.fieldName === 'districtId');
      district.itemList = tl;
      district.initialValue = '';
    },
    async init() {
      console.log(this.dataType);
      await getUserInfo().then(res => {
        if (res.resultCode == 200) {
          this.userId = res.data.userInfo.userId;
          // console.log('self',this.userId)
        }
      });
      // 车型
      vehicleConfigurationNew(0, { isUnlimited: 10041001 })
        .then(res => {
          this.topFilterList.find(item => item.fieldName === 'inteCarType').itemList = res.data;
        })
        .catch(err => {
          // console.log(err)
        });
      // 查询所属顾问
      let roleType = this.dataType === 'clue' ? '10061012' : '10061012,10061015';
      this.getConsultant(1, roleType, 2020141).then(result => {
        this.topFilterList.find(item => item.fieldName === 'consultants').itemList = result;
      });

      // 查询内饰颜色
      let user = await getLoginUser({});
      if ('beijing' == user.data.appId) {
        this.topFilterList.find(item => item.fieldName === 'interiorColor').hidden = true;
      }
      //console.log(user.data.appId, 'we2rwevsdvdv');
      await getAllColorByAppIdAndType({ appId: user.data.appId, colorType: '16081001' }).then(result => {
        this.topFilterList.find(item => item.fieldName === 'interiorColor').itemList = result.data.map(x => ({ value: `${x.colorId}`, text: x.colorName }));
      });
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '关键字',
          fieldName: 'customerOrPhone',
          placeholder: '客户名称/手机号'
        },
        {
          type: 'RANGE_DATE',
          label: '下发/创建时间',
          fieldName: 'dateStart|dateEnd',
          //dateType: 'exactdaterange',
          dateType: 'datetimerange',
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '线索热度',
          fieldName: 'temperatures',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT_TREE',
          label: '来源渠道',
          fieldName: 'clueSourceIds',
          defaultExpandAll: true,
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT_CASCADER',
          label: '意向车型',
          fieldName: 'inteCarType',
          placeholder: '请选择',
          options: { titles: ['品牌', '车系', '车型', '配置', '选装', '颜色'] },
          itemList: []
        },
        {
          type: 'SELECT',
          label: '所属顾问',
          fieldName: 'consultants',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '内饰颜色',
          fieldName: 'interiorColor',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '线索类型',
          fieldName: 'clueEnterTypes',
          placeholder: '请选择',
          itemList: this.createDictList('7019')
        },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [], change: props => this.initCity(props) },
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [], change: props => this.initTown(props) },
        { type: 'SELECT', label: '县区', fieldName: 'districtId', placeholder: '请选择', initialValue: '', itemList: [] },
        {
          type: 'SELECT',
          label: '订金类型',
          fieldName: 'depositType',
          placeholder: '请选择',
          itemList: this.createDictList('8050')
        },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'customerTypes',
          placeholder: '请选择',
          itemList: this.createDictList('1523')
        },
        // {
        //   type: 'SELECT',
        //   label: '逾期未处理',
        //   fieldName: 'overTime',
        //   placeholder: '请选择',
        //   itemList: this.createDictList('1004')
        // },
        {
          type: 'SELECT',
          label: '线索状态',
          fieldName: 'clueStatus',
          placeholder: '请选择',
          itemList: this.createDictList('7000')
        },
        {
          type: 'RANGE_DATE',
          label: '确认时间',
          fieldName: 'confirmTimeStart|confirmTimeEnd',
          dateType: 'exactdaterange',
          placeholder: ''
        },
        {
          type: 'INPUT',
          label: '来源备注',
          fieldName: 'sourceRemark',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '线索评级等级',
          fieldName: 'mapClueLevel',
          hidden: getAppId() == 'beijing' ? false : true,
          placeholder: '请选择',
          itemList: [
            { value: 1, text: '一' },
            { value: 2, text: '二' },
            { value: 3, text: '三' },
            { value: 4, text: '四' },
            { value: 5, text: '五' }
          ]
        }
      ];
    },
    editHandle(row) {
      debugger
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button
                  size="mini"
                  type="text"
                  onClick={() => this.editHandle(props.row)}
                >
                  明细
                </multiuse-button>
              </div>
            );
          }
        },

        {
          title: '客户名称',
          dataIndex: 'customerName',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1523'),
          render: props => {
            return <span>{this.createDictText(props.row.customerType, '1523')}</span>;
          }
        },
        {
          title: '线索评级等级',
          dataIndex: 'mapClueLevel',
          hidden:getAppId()=='beijing'?false:true,
          align: 'center',
          render: props => {
            return <el-rate disabled={true} v-model={props.row.mapClueLevel}></el-rate>;
          }
        },
        {
          title: '订金类型',
          dataIndex: 'depositType',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('8050'),
          render: props => {
            return <span>{this.createDictText(props.row.depositType, '8050')}</span>;
          }
        },
        {
          title: '订金金额',
          dataIndex: 'depositAmount',
          sorter: true,
          filter: true,
          width: 150,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '性别',
          dataIndex: 'gender',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1002'),
          render: props => {
            return <span>{this.createDictText(props.row.gender, '1002')}</span>;
          }
        },
        {
          title: '手机号码',
          dataIndex: 'mobilePhone',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '意向品牌',
          dataIndex: 'inteBrandName',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '意向车系',
          dataIndex: 'inteCarSeriesName',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '意向车型',
          dataIndex: 'inteCarTypeName',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '意向配置',
          dataIndex: 'inteYearStyleName',
          filter: true,
          align: 'center',
          width: 220,
          filterType: 'input'
        },
        {
          title: '意向选装',
          dataIndex: 'inteOptionName',
          filter: true,
          align: 'center',
          width: 220,
          filterType: 'input'
        },
        {
          title: '意向颜色（外饰）',
          dataIndex: 'inteColourName',
          filter: true,
          align: 'center',
          width: 180,
          filterType: 'input'
        },
        {
          title: '意向颜色（内饰）',
          dataIndex: 'interiorColorName',
          filter: true,
          align: 'center',
          width: 180,
          filterType: 'input'
        },
        {
          title: '所属顾问',
          dataIndex: 'consultantName',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '创建时间',
          dataIndex: 'caeateAt',
          sorter: true,
          width: 150,
          align: 'center',
          render: props => {
            return <span>{formatDates(props.row.caeateAt)}</span>;
          }
        },
        {
          title: '下发时间',
          dataIndex: 'manufacturerIssueDate',
          sorter: true,
          width: 150,
          align: 'center',
          render: props => {
            return <span>{formatDates(props.row.manufacturerIssueDate)} </span>;
          }
        },
        {
          title: '是否重复',
          dataIndex: 'isRepeat',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isRepeat, '1004')}</span>;
          }
        },
        {
          title: '计划首次跟进时间',
          dataIndex: 'firstTouchTime',
          sorter: true,
          align: 'center',
          filterType: 'checkbox',
          render: props => {
            return <span>{formatDates(props.row.firstTouchTime)}</span>;
          }
        },
        {
          title: '最后跟进时间',
          dataIndex: 'lateTouchTime',
          sorter: true,
          align: 'center',
          filterType: 'checkbox',
          render: props => {
            return <span>{formatDates(props.row.lateTouchTime)}</span>;
          }
        },
        // {
        //   title: '逾期未处理',
        //   dataIndex: 'isOverTime',
        //   align: 'center',
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1004'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.isOverTime, '1004')}</span>;
        //   }
        // },
        {
          title: '确认时间',
          dataIndex: 'affrimTime',
          sorter: true,
          width: 180,
          align: 'center',
          filterType: 'checkbox',
          render: props => {
            return <span>{formatDates(props.row.affrimTime)}</span>;
          }
        },
        {
          title: '线索热度',
          dataIndex: 'temperature',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7018'),
          render: props => {
            return <span>{this.createDictText(props.row.temperature, '7018')}</span>;
          }
        },
        {
          title: '线索类型',
          dataIndex: 'clueType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7019'),
          render: props => {
            return <span>{this.createDictText(props.row.clueType, '7019')}</span>;
          }
        },
        {
          title: '线索状态',
          dataIndex: 'clueStatus',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7000'),
          render: props => {
            return <span>{this.createDictText(props.row.clueStatus, '7000')}</span>;
          }
        },
        {
          title: '来源渠道',
          dataIndex: 'clueSourceName',
          filter: true,
          width: 150,
          filterType: 'input'
        },
        {
          title: '来源备注',
          dataIndex: 'sourceRemark',
          width: 150,
          filterType: 'input'
        },
        {
          title: '其它来源',
          dataIndex: 'otherSource',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7065'),
          render: props => {
            return <span>{this.createDictText(props.row.otherSource, '7065')}</span>;
          }
        },
        {
          title: '预购日期',
          dataIndex: 'bookingDate',
          sorter: true,
          width: 180,
          align: 'center',
          render: props => {
            return <span>{formatDates(props.row.bookingDate)} </span>;
          }
        },
        {
          title: '当前线索出现的个数',
          dataIndex: 'clueCountNum',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '省',
          dataIndex: 'provinceName',
          align: 'center',
          width: 150,
          filterType: 'input'
        },
        {
          title: '市',
          dataIndex: 'cityName',
          align: 'center',
          width: 150,
          filterType: 'input'
        },
        {
          title: '区',
          dataIndex: 'districtName',
          align: 'center',
          width: 150,
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          width: 150,
          filterType: 'input'
        },
        {
          title: 'CC清洗备注',
          dataIndex: 'ccInvalidReason',
          align: 'center',
          width: 150,
          filterType: 'input'
        }
      ];
    },
    selectChangeHandle(rows) {
      // console.log('rows', rows);
      // if (!rows.length) return;
      this.selectedRows = rows;
    },
    // 新增
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    // 导入
    importHandle() {
      this.handleType = 'import';
      this.UploadFileIsShow = true;
      this.form.fileList = [];
    },
    successHandler(val) {
      if (val && val.length > 0) {
        console.log(val, '导入');
        this.form.fileList = val;
      }
      this.UploadFileIsShow = false;
      // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },

    // 导出
    async exportHandle(row) {

      let json = Object.assign({}, { CODE: 'CODE_0000016' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // let params = JSON.parse(JSON.stringify(this.fetchParams));

      // this.handleType = 'export';
      // this.exportLoading = true;
      // await exportClues({ ...params, userId: this.userId })
      //   .then(response => {
      //     // console.log(response,"response")
      //     exportExcelFile(response.data, '线索管理');
      //     this.exportLoading = false;
      //   })
      //   .catch(err => {
      //     this.exportLoading = false;
      //     console.log(err);
      //   });

      //     this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //         confirmButtonText: '下载',
      //         cancelButtonText: '取消',
      //         type: 'warning'
      //       }).then(() => {
      //           exportClues({...params, userId: this.userId}).then( response => {
      //             console.log(response,"response")
      //             exportExcelFile(response.data,'线索管理');
      //             this.exportLoading = false;
      //           }).catch( err => {
      //             console.log(err)
      //           })
      //       }).catch(() => {
      //         console.log('456')
      //         this.$message({
      //           type: 'info',
      //           message: '已取消'
      //         });
      //       });
    },
    // 下载
    downHandle() {
      this.handleType = 'down';
      this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          debugger;
          downloadExcel()
            .then(response => {
              console.log(response, 'response');
              exportExcelFile(response.data, '线索管理');
              this.exportLoading = false;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          console.log('456');
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    showHandler() {
      debugger
      this.dialogTitle = `线索管理${this.conf[this.handleType]}`;
      this.visible = true;
    },
    // 来源渠道限制
    deepListClone(data) {
      let tempList = [];
      // console.log('deepListClone',Object.prototype.toString.call(data),data)
      if (data && data.length && Object.prototype.toString.call(data) == '[object Array]') {
        for (let i in data) {
          if (data[i].children && [].concat(data[i].children).length > 0) {
            tempList[i] = {
              text: data[i].clueName,
              value: data[i].value,
              parentId: data[i].parentId,
              disabled: true,
              businessType: data[i].businessType,
              children: this.deepListClone([].concat(data[i].children))
            };
          } else {
            tempList[i] = {
              text: data[i].clueName,
              value: data[i].value,
              parentId: data[i].parentId,
              disabled: false,
              businessType: data[i].businessType
            };
          }
        }
      }
      return tempList;
    },
    // 来源渠道
    async getClueTree() {
      const res = await queryClueSourceList();
      // console.log('来源渠道', res)
      let treeList = res.data;
      treeList.forEach(el => (el.text = el.clueName));
      treeList.forEach(el => (el.value = el.value));
      treeList.forEach(el => (el.parentId = el.parentId));

      //只有叶子节点可以点击
      // let treeList = this.deepListClone([].concat(res.data));
      this.topFilterList.find(item => item.fieldName === 'clueSourceIds').itemList = treeList;
    },
    async getAllHeatUp() {
      const res = await getAllHeatUp({ isValid: 10041001 });
      console.log('线索热度定义', res);
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'temperatures').itemList = res.data.map(x => ({ value: x.id, text: x.clueHeatName }));
      }
    },
    changeHandle(val) {
      // console.log('val', val)
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initProvince();
  }
};
</script>

<style lang="less" scoped>
</style>
